package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.trkj.dao.jpa.IDepositTableDao;
import com.trkj.dao.jpa.ILiveinrecordTableDao;
import com.trkj.dao.jpa.IPayTableDao;
import com.trkj.dao.jpa.ITallyTableDao;
import com.trkj.dao.jpa.ITallydetailsTableDao;
import com.trkj.dao.mybatis.TallyTableMapper;
import com.trkj.pojos.DepositTable;
import com.trkj.pojos.LiveinrecordTable;
import com.trkj.pojos.PayTable;
import com.trkj.pojos.TallyTable;
import com.trkj.pojos.TallydetailsTable;
import com.trkj.vo.PayVo;
import com.trkj.vo.TallyTableVo;

@Service
@Transactional
public class TallyService {
	@Autowired
	private TallyTableMapper tallyTableMapper;
	@Autowired
	private ITallyTableDao iTallyTableDao;
	@Autowired
	private IDepositTableDao iDepositTableDao;
	@Autowired
	private ILiveinrecordTableDao iLiveinrecordTableDao;
	@Autowired
	private ITallydetailsTableDao iTallydetailsTableDao;
	@Autowired
	private IPayTableDao iPayTableDao;

	/**
	 * 根据住院号分页查询每日记账单
	 * 
	 * @param page
	 * @param rows
	 * @param liveID
	 * @return
	 */
	public Map<String, Object> queryTallyByLiveID(int page, int rows, String liveID) {

		Map<String, Object> map = new HashMap<>();
		Page<TallyTable> p = PageHelper.startPage(page, rows, true);
		List<TallyTable> list = tallyTableMapper.findAllTallyByLiveID(liveID);

		map.put("total", p.getTotal());
		map.put("rows", list);

		return map;

	}
	/**
	 * 根据住院号分页查询未核算的每日记账单
	 * 
	 * @param page
	 * @param rows
	 * @param liveID
	 * @return
	 */
	public Map<String, Object> queryNoAccountTallyByLiveID(int page, int rows, String liveID) {

		Map<String, Object> map = new HashMap<>();
		Page<TallyTable> p = PageHelper.startPage(page, rows, true);
		List<TallyTable> list = tallyTableMapper.findAllTallyByLiveIDAndNoAccount(liveID);

		map.put("total", p.getTotal());
		map.put("rows", list);

		return map;

	}
	/**
	 * 根据住院号分页查询已核算未结算的每日记账单
	 * 
	 * @param page
	 * @param rows
	 * @param liveID
	 * @return
	 */
	public Map<String, Object> queryHasNoPayAccountTallyByLiveID(int page, int rows, String liveID) {

		Map<String, Object> map = new HashMap<>();
		Page<TallyTable> p = PageHelper.startPage(page, rows, true);
		List<TallyTable> list = tallyTableMapper.findAllTallyByLiveIDAndNoPayHasAccount(liveID);

		map.put("total", p.getTotal());
		map.put("rows", list);

		return map;

	}

	/**
	 * 根据住院号分页查询缴费账单
	 * 
	 * @param page
	 * @param rows
	 * @param liveID
	 * @return
	 */
	public Map<String, Object> queryPayByLiveID(int page, int rows, String liveID) {

		Map<String, Object> map = new HashMap<>();
		Page<PayTable> p = PageHelper.startPage(page, rows, true);
		List<PayTable> list = tallyTableMapper.findAllPayByLiveID(liveID);

		map.put("total", p.getTotal());
		map.put("rows", list);

		return map;

	}

	/**
	 * 返回收费项目的树结构
	 * 
	 * @return
	 */
	public List<Map<String, Object>> queryAllchargeTypeTotree() {

		List<Map<String, Object>> resultList = new ArrayList<>();

		List<Map<String, Object>> list = tallyTableMapper.findAllChargetypeToTree();

		for (Map<String, Object> map : list) {
			Map<String, Object> resultmap = new HashMap<>();
			resultmap.put("id", map.get("CHARGETYPEID"));
			resultmap.put("text", map.get("CHAEGENAME"));
			resultList.add(resultmap);
		}

		return resultList;

	}

	/**
	 * 根据类型查询收费项目
	 * @param page
	 * @param rows
	 * @param typeID
	 * @return
	 */
	public Map<String, Object> queryChargeProjectByTypeID(int page, int rows, Long typeID) {

		Page<Map<String, Object>> p = PageHelper.startPage(page, rows, true);
		List<Map<String, Object>> list = tallyTableMapper.findChargeProjectByType(typeID);

		Map<String, Object> resultmap = new HashMap<>();
		resultmap.put("rows", list);
		resultmap.put("total", p.getTotal());
		return resultmap;
	}
	/**
	 * 根据name查询收费项目
	 * @param page
	 * @param rows
	 * @param typeID
	 * @return
	 */
	public Map<String, Object> queryChargeProjectByName(int page, int rows, String name) {

		Page<Map<String, Object>> p = PageHelper.startPage(page, rows, true);
		List<Map<String, Object>> list = tallyTableMapper.findChargeProjectByName(name);

		Map<String, Object> resultmap = new HashMap<>();
		resultmap.put("rows", list);
		resultmap.put("total", p.getTotal());
		return resultmap;
	}
	/**
	 * 创建新的账单号
	 * @return
	 */
	public String CreateTallyID(){
		String newTallyID = "";
		//将当前日期格式化为纯数字
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(new Date()).substring(2, 8);
		String LikeID = "%" + str + "%";
		List<String> list = iTallyTableDao.findTallyID(LikeID);
		
		if(list.isEmpty()){
			newTallyID = "TD" + str +"0001";
		}else{
			List<Integer> lists = new ArrayList<>();
			for(int i=0;i<list.size();i++){
				lists.add(Integer.valueOf(list.get(i).toString().substring(8, 12)));
			}
			//Collections.max取最大值再加1，拼接住院号
			 int next = Collections.max(lists).intValue()+1;
			 String nextID = String.format("%04d", next);
			 newTallyID = "TD" + str + nextID;
		}
		return newTallyID;
	}
	/**
	 * 查询病人余额，未结费用，缴纳押金
	 * @param liveID
	 * @return
	 */
	public Map<String,Object> queryTallyBalance(String liveID){
		BigDecimal alltally = tallyTableMapper.sumAllTally(liveID);//查询住院全部住院消费
		alltally = (alltally==null)?new BigDecimal(0):alltally;
		
		BigDecimal hasPay = tallyTableMapper.sumHasPayTally(liveID);//查询已经结算费用
		hasPay = (hasPay==null)?new BigDecimal(0):hasPay;
		
		BigDecimal nopay = tallyTableMapper.sumNoPayTally(liveID); //查询未结费用
		nopay = (nopay==null)?new BigDecimal(0):nopay;
	
		List<DepositTable> list =  iDepositTableDao.findByLiveid5(liveID);
		
		BigDecimal deposit  = list.get(0).getDepositlimit4();//查询押金
		
		BigDecimal balance =deposit.subtract(nopay); //计算余额
		
		
		Map<String,Object> map = new HashMap<>();
		map.put("balance", balance);
		map.put("nopay", nopay);
		map.put("deposit", deposit);
		map.put("haspay", hasPay);
		map.put("alltally", alltally);
		
		return map;
		
	}
	
	/**
	 * 创建新的账单详情号
	 * @return
	 */
	public String CreateTallyDetialID(){
		String newTallyDetialID = "";
		//将当前日期格式化为纯数字
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(new Date()).substring(2, 8);
		String LikeID = "%" + str + "%";
		List<String> list = iTallyTableDao.findTallyID(LikeID);
		
		if(list.isEmpty()){
			newTallyDetialID = "TI" + str +"0001";
		}else{
			List<Integer> lists = new ArrayList<>();
			for(int i=0;i<list.size();i++){
				lists.add(Integer.valueOf(list.get(i).toString().substring(8, 12)));
			}
			//Collections.max取最大值再加1，拼接住院号
			 int next = Collections.max(lists).intValue()+1;
			 String nextID = String.format("%04d", next);
			 newTallyDetialID = "TI" + str + nextID;
		}
		return newTallyDetialID;
	}
	/**
	 * 添加账单
	 * @param tallyTableVo
	 */
	public void addTally(TallyTableVo tallyTableVo){
		
		String liveID  = tallyTableVo.getLiveID();
		LiveinrecordTable liveinrecordTable = iLiveinrecordTableDao.findOne(liveID);//查询住院登记
		
		TallyTable tallyTable = tallyTableVo.getTallyTable();//账单与住院登记建立关系
		
		tallyTable.setLiveinrecordTable(liveinrecordTable);
		iTallyTableDao.save(tallyTable);//保存账单*/
		
		List<TallydetailsTable> list = Arrays.asList(tallyTableVo.getTallydetailsTables());
		
		List<String> createTDid = createTDid(list.size());
		
		for(int i=0;i<list.size();i++){
			list.get(i).setTallydetailsid(createTDid.get(i));
			list.get(i).setTallyTable(tallyTable);
		}
		iTallydetailsTableDao.save(list);
	}
	/**
	 * 解决事物未提交时不能创建多个账单ID的BUG
	 * @param chang
	 * @return
	 */
	public List<String> createTDid(int chang){
		
		List<String> list = new ArrayList<>();
		
		String newID = CreateTallyDetialID();
		list.add(newID);
		String firstID = newID.substring(0, newID.length()-4);
		String nextID;
		
		String newTallyDetialID;
		
		int intid = Integer.valueOf(newID.substring(newID.length()-4));
		
		for(int i=1;i<chang;i++){
			 nextID = String.format("%04d", intid+i);
			 newTallyDetialID =firstID + nextID;
			 list.add(newTallyDetialID);
		}
		return list;
		
	}
	/**
	 * 查询未核算账单
	 * @return
	 */
	public List<Map<String,Object>> queryNoAcountTally(){
		
		List<Map<String,Object>> map = tallyTableMapper.findNoAcountTally();
		
		return map;
	}
	/**
	 * 根据账单号查询未核算详情
	 * @param tallyID
	 * @return
	 */
	public List<TallydetailsTable> queryAllNoAccountTallydetailsByTallyID(String tallyID){
		return tallyTableMapper.findAllNoAccountTallydetailsByTallyID(tallyID);
	}
	/**
	 * 根据账单号查询详情
	 * @param tallyID
	 * @return
	 */
	public List<TallydetailsTable> queryAllTallydetailsByTallyID(String tallyID){
		return tallyTableMapper.findAllTallydetailsByTallyID(tallyID);
	}
	/**
	 * 根据账单详情ID进行删除
	 * @param TallyDetailID
	 * @param TallyID
	 */
	public boolean deleteTallyDetail(String TallyDetailID,BigDecimal deleteSum ){
		
		try {
			
			String TallyID = iTallydetailsTableDao.findOne(TallyDetailID).getTallyTable().getTallyid();//获取账单ID
			TallyTable findOne = iTallyTableDao.findOne(TallyID);//查询账单
			
			iTallydetailsTableDao.delete(TallyDetailID);//删除子记录
				
			List<TallydetailsTable> tallydetailsTables = findOne.getTallydetailsTables();
			if(tallydetailsTables.isEmpty() || tallydetailsTables.size() - 1 == 0){
				iTallyTableDao.delete(findOne);
			}else{
				BigDecimal tallytotal = findOne.getTallytotal();
				BigDecimal newtallytotal = tallytotal.subtract(deleteSum);
				findOne.setTallytotal(newtallytotal);//修改账单总价
				iTallyTableDao.save(findOne);//保存
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 修改账单详情状态
	 * @param TalltdetialID
	 */
	public boolean accountTally(String TalltdetialID){
		
		try {
			TallydetailsTable findOne = iTallydetailsTableDao.findOne(TalltdetialID);
			findOne.setTallydetailsstatus("已核算");
			iTallydetailsTableDao.save(findOne);//修改核算状态
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 修改账单状态
	 * @param detialID
	 * @return
	 */
	public boolean changeTallyAccountStatus(String detialID){
		
		try {
			TallyTable tallyTable = iTallydetailsTableDao.findOne(detialID).getTallyTable();
			tallyTable.setTallystatus("已核算");
			iTallyTableDao.save(tallyTable);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 创建新的缴费单号
	 * @return
	 */
	public String CreatePayID(){
		String newPayID = "";
		//将当前日期格式化为纯数字
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String str = sdf.format(new Date()).substring(2, 8);
		String LikeID = "%" + str + "%";
		List<String> list = iPayTableDao.queryReturnPayID(LikeID);
		
		if(list.isEmpty()){
			newPayID = "PY" + str +"0001";
		}else{
			List<Integer> lists = new ArrayList<>();
			for(int i=0;i<list.size();i++){
				lists.add(Integer.valueOf(list.get(i).toString().substring(8, 12)));
			}
			//Collections.max取最大值再加1，拼接住院号
			 int next = Collections.max(lists).intValue()+1;
			 String nextID = String.format("%04d", next);
			 newPayID = "PY" + str + nextID;
		}
		return newPayID;
	}
	/**
	 * 新增支付记录修改账单状态
	 * @param payVo
	 * @return
	 */
	public boolean addNewPayTally(PayVo payVo){
		
		try {
			LiveinrecordTable liveR = iLiveinrecordTableDao.findOne(payVo.getLiveInId());
			PayTable payTable = payVo.getPayTable();
			payTable.setLiveinrecordTable(liveR);//与住院表建立关系
			iPayTableDao.save(payTable);//保存
			
			String[] tid = payVo.getTid();
			for (String string : tid) {
				TallyTable tally = iTallyTableDao.findOne(string);
				tally.setPaystatus2("已结算");//修改支付状态
				iTallyTableDao.save(tally);//保存
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	
	
	
	
	
	
	
}
